#include "core.h"

int echo(string data, connection_t* conn, core_data_t& core_data)
{
    if(conn == nullptr) return -1;

    Socket temp(conn->fd, CLIENT_SOCKET);
    char* current = &(*data.begin());
    size_t bytes_left = data.size();
    size_t bytes_total = data.size();
    int ret;
    {
        std::lock_guard<std::mutex> writerLock(conn->writerLock);
        while((ret = temp.Send(current, data.size())) > 0)
        {
            bytes_left -= ret;
            current += ret;
            if(bytes_left == 0) break;
        }
    }
    if(bytes_left == 0){ 
        std::cout << "数据发送完毕，发送数据为" << data << std::endl;
        return 1; //已经发送完，返回1
    }
    //未发送完，查看errno
    if(ret < 0){
        if(temp.getErrorno() == EAGAIN){
            //内核缓冲区已满
            if(conn->writer.get() == nullptr) //没有注册过写事件
            {
                string* buffer = new string(data); 
                responder* res = new responder(conn->fd, buffer, buffer->size()); //一定要确认responder管理了buffer
                conn->writer.reset(res);
                epoll_event temp = core_data.epoll.setEpollEvent(conn->fd, EPOLLOUT | EPOLLET, (void*)conn);
                core_data.epoll.epollAddEvent(temp, conn->fd);
            }else{  //已经注册了写事件
                responder* temp = conn->writer.get();
                if(temp->bytes_left > 0){ //仍有未发送的字节
                    std::lock_guard<std::mutex> lock(temp->responder_lock);
                    temp->buffer->append(data, bytes_total-bytes_left, bytes_left); //将剩余未发送数据append到buffer后面
                    temp->bytes_left += bytes_left;
                    temp->bytes_total += bytes_left;
                }else{
                    //没有未发送的数据但是没有关闭写事件
                    return -1; //先返回错误，有问题后续再改
                }
            }
            return 0;
        }else{
            return -1;
        }
    }
}